package com.sike.netty.im.server.handler;

import com.sike.netty.im.common.command.ExitGroupRequestCommand;
import com.sike.netty.im.common.command.ExitGroupResponseCommand;
import com.sike.netty.im.common.command.Message;
import com.sike.netty.im.common.command.MessageBuilder;
import com.sike.netty.im.server.service.BeanFactory;
import com.sike.netty.im.server.service.GroupService;
import com.sike.netty.im.server.service.SessionService;
import com.sike.netty.im.server.service.UserInfoCache;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 退出群聊 handler
 *
 * @author chenssy
 * @date 2023/09/22
 */
public class ExitGroupRequestHandler extends SimpleChannelInboundHandler<ExitGroupRequestCommand> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ExitGroupRequestCommand msg) throws Exception {
        // 获取当前用户名
        SessionService sessionService = (SessionService) BeanFactory.getServiceBean(SessionService.class);
        String userId = sessionService.getUserIdByChannel(ctx.channel());
        String userName = UserInfoCache.getUserInfoByUserId(userId).getUserName();

        // 退出群聊
        GroupService groupService = (GroupService) BeanFactory.getServiceBean(GroupService.class);
        String groupKey = groupService.exitGroup(msg.getGroupId(),userName);

        ExitGroupResponseCommand responseCommand = new ExitGroupResponseCommand();
        responseCommand.setGroupId(groupKey.split("-")[0]);
        responseCommand.setGroupName(groupKey.split("-")[1]);
        Message message = MessageBuilder.buildMessage(responseCommand,null,null);
        ctx.writeAndFlush(message);
    }
}
